package com.hatom.cameraxhelp.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Environment;
import android.util.Log;

import com.googlecode.tesseract.android.TessBaseAPI;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @auther liuhao17
 * @date 2018/5/10
 */
public class IDCardOCRHelper {

    private TessBaseAPI mBaseApi;
    private String mSdPath;
    private volatile boolean finishInit = false;
    private CountDownLatch closeLatch;
    private final static long TIMEOUT = 5;
    private volatile static IDCardOCRHelper idCardOCRHelper;
    private static final String language="eng";

    public static IDCardOCRHelper getInstance(Context context) {
        if (idCardOCRHelper == null) {
            synchronized (IDCardOCRHelper.class) {
                if (idCardOCRHelper == null) {
                    idCardOCRHelper = new IDCardOCRHelper(context);
                }
            }
        }
        return idCardOCRHelper;
    }


    public IDCardOCRHelper(Context context) {
        mSdPath = Environment.getExternalStorageDirectory() + "/ayy/";
        File file = new File(Environment.getExternalStorageDirectory() + "/ayy");
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            copyAssetFile(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean copyAssetFile(Context context) throws Exception {
        String dir = mSdPath + "/tessdata";
        String filePath = mSdPath + "/tessdata/"+language+".traineddata";
        File f = new File(dir);
        if (!f.exists()) {
            f.mkdirs();
        }
        File dataFile = new File(filePath);
        if (dataFile.exists()) {
            return true;// 文件存在
        } else {
            InputStream in = context.getResources().getAssets().open(language+".traineddata");

            File outFile = new File(filePath);
            if (outFile.exists()) {
                outFile.deleteOnExit();
            }
            OutputStream out = new FileOutputStream(outFile);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
        return true;
    }

    public synchronized void init() {
        try {
            if (closeLatch != null) {
                closeLatch.await(TIMEOUT, TimeUnit.SECONDS);
                closeLatch = null;
            }
            long time = System.currentTimeMillis();
            Log.e("ScanActivity", "init " + time);
            mBaseApi = new TessBaseAPI();
            mBaseApi.init(mSdPath, language);
            mBaseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
           // mBaseApi.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST,"~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……& amp;*（）ˇ〈〉〔〕一′`\"‖『』「」——_+|{}【】‘；：”“’。，、？|--]");
            mBaseApi.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, "0123456789Xx");
            Log.e("ScanActivity", "init end " + (System.currentTimeMillis() - time));
            finishInit = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public synchronized String doOCRAnalysis(Bitmap bitmap) {
        Bitmap bitmap8888 = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        mBaseApi.setImage(bitmap8888);
        String text = mBaseApi.getUTF8Text();
        mBaseApi.clear();
        bitmap8888.recycle();
        return text;
    }
    public boolean hasInit() {
        return finishInit;
    }

    public synchronized void close() {
        if (!finishInit) {
            closeLatch = new CountDownLatch(1);
            mBaseApi.end();
            closeLatch.countDown();
        }
    }

}
